<template>
  <AppModal ref="modalRef" width="500px">
    <a-form ref="formRef" :model="formModel" :label-col="{ style: { width: '90px' } }">
      <a-form-item
        :label="type + '名称'"
        name="name"
        :rules="[{ required: true, message: '此为必填项' }]"
      >
        <a-input :placeholder="`请输入${type}名称`" v-model:value="formModel.name"></a-input>
      </a-form-item>
      <a-form-item
        :label="type + '编码'"
        name="code"
        :rules="[{ required: true, message: '此为必填项' }]"
      >
        <a-input
          :disabled="modalAction != 'add'"
          :placeholder="`请输入${type}编码`"
          v-model:value="formModel.code"
        ></a-input>
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea placeholder="请输入备注" v-model:value="formModel.remark"></a-textarea>
      </a-form-item>
      <a-form-item label="排序">
        <a-input-number v-model:value="formModel.weight"></a-input-number>
      </a-form-item>
    </a-form>
  </AppModal>
</template>

<script setup lang="ts">
import { AppModal } from '@/components/common'
import { useForm } from '@/hooks/useForm.ts'
import { DictDto } from '@/api/dict.ts'
import { useModal } from '@/hooks/useModal.ts'
import { message } from 'ant-design-vue'

const props = defineProps<{
  type: string
}>()
const emits = defineEmits(['add', 'update'])
const { formRef, formModel, validation, restFields, initForm } = useForm<DictDto>({
  name: null,
  code: null,
  remark: '',
  weight: 0,
})
const { modalRef, okLoading } = useModal()
const modalAction = ref('')

function onOpen(action: string, row?: DictDto) {
  modalAction.value = action
  initForm()
  if (row) {
    formModel.value = { ...row }
  }

  restFields()
  modalRef.value.open({
    title: action == 'add' ? '新增' + props.type : '编辑' + props.type,
    onOk: onSubmit,
  })
}

function onSubmit() {
  validation().then(() => {
    okLoading.value = true
    if (modalAction.value == 'add') {
      emits('add', unref(formModel), () => {
        okLoading.value = false
        modalRef.value.close()
        message.success('添加成功')
      })
    } else {
      emits('update', unref(formModel), () => {
        okLoading.value = false
        modalRef.value.close()
        message.success('更新成功')
      })
    }
  })

  return false
}

defineExpose({ onOpen })
</script>

<style scoped></style>
